/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.comut.crud.bo;

import com.comut.crud.dao.PoiDao;
import com.comut.crud.ejb.interfaces.IPoiAction;
import com.comut.crud.pojo.FindAndSet;
import com.comut.crud.pojo.mobile.POIInfo;
import com.comut.crud.pojo.poi.Poi;
import com.comut.crud.util.ParseJson;
import com.comut.crud.util.Util;
import com.comut.lib.error.ErrorCodes;
import com.comut.lib.exception.JSONMalFormedException;
import com.comut.lib.exception.ObjectFoundException;
import com.comut.lib.exception.ObjectNotFoundException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author asantos
 */
public class PoiHandler implements IPoiAction {

    private static Logger _logger = Logger.getLogger(PoiHandler.class.getName());
    private Connection _connection;
    private PoiDao poiDao;

    public PoiHandler(Connection connection) {
        this._connection = connection;
        poiDao = new PoiDao(_connection);

    }

    public Poi insertPoi(Poi poi) throws ObjectFoundException {
        if (poi.isValid()) {
            poi.setParameters(ParseJson.getInstance().createXml(poi));
            int id = poiDao.createPoi(poi);
            Poi toRet = new Poi();
            toRet.setId(id);
            _logger.info(toRet.toString());
            return toRet;
        } else {
            throw new JSONMalFormedException("The mandatory attributes are not in json.", ErrorCodes.JSON_MAL_FORMED);
        }
    }

    public void deletePoi(Poi poi) throws ObjectNotFoundException {
        _logger.info(poi.toString());
        poiDao.deletePoi(poi.getId());
    }

    public void updatePoi(String poi) throws ObjectNotFoundException {
        _logger.info(poi.toString());
        //check if the BasicDBObject is well formed
        FindAndSet fas = ParseJson.getInstance().buildSQLQueryForPoi(poi, ParseJson.getInstance().getPoiFind(), ParseJson.getInstance().getPoiUpdate(),
                ParseJson.getInstance().getPoiFindStr(), ParseJson.getInstance().getPoiUpdateStr());
        if (fas.getPoi() != null && fas.getPoi().updateXml()) {
            fas.getPoi().setId(Integer.parseInt(Util.cutFirstAndLastChars(fas.getFind().substring(fas.getFind().indexOf("=") + 1).trim())));
            String previousXml = poiDao.getParameters(fas.getPoi().getId() + "");
            fas.getPoi().setParameters(ParseJson.getInstance().updateXml(fas.getPoi(), previousXml));
        }
        //update the poi
        poiDao.updatePoi(fas);
    }
    
    /**
     *  @author celia calcada
     *  ...
     */
    public Poi getPoi(Poi poi) throws ObjectNotFoundException {

        ResultSet rs = poiDao.getPoi(poi.getId());
        Poi toRet = new Poi();
        try {
            if (rs.next()) {
                toRet.setId(poi.getId());
            }
        } catch (SQLException ex) {
            _logger.error(ex);
        }

        _logger.info(toRet.toString());
        return toRet;
    }

    /**
     *   
     * Issue: IFL-1568
     * @author celia calcada
     * @param userId
     * @return
     */
    public POIInfo[] getPOIsForUserId(int userId) {
        ResultSet resultSet = poiDao.getPOIsForUserId(userId);

        ArrayList<POIInfo> list = new ArrayList<POIInfo>();

        try {
            while (resultSet.next()) {
                POIInfo poiInfo = new POIInfo();
                poiInfo.setId(resultSet.getInt("Id"));
                poiInfo.setName(resultSet.getString("Name"));
                poiInfo.setCategory(resultSet.getString("Category"));
                
                if( resultSet.getBoolean("State") == true){
                    poiInfo.setState("Validated");
                }
                else{
                    poiInfo.setState("Not validated");
                }
                
                poiInfo.setRadius(resultSet.getInt("Radius"));
                poiInfo.setLatitude(resultSet.getDouble("Latitude"));
                poiInfo.setLongitude(resultSet.getDouble("Longitude"));
                poiInfo.setDescription(resultSet.getString("Description"));
                poiInfo.setMaximumTimeOfPermanence(resultSet.getInt("MaximumTimeOfPermanence"));
                
                list.add(poiInfo);
            }
        } catch (SQLException ex) {
            _logger.error(ex);
        }

        POIInfo[] ret = new POIInfo[list.size()];
        return list.toArray(ret);
    }
}
